using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 
/// </summary>
public class XConsoleToScreen : MonoBehaviour
{
    const int MAX_LINES         = 50;
    const int MAX_LINES_LENGTH  = 120;

    /// <summary>
    /// 
    /// </summary>
    private string logStr = "";

    /// <summary>
    /// 
    /// </summary>
    private readonly List<string> lines = new List<string>();

    /// <summary>
    /// 
    /// </summary>
    public int fontSize = 15;

    /// <summary>
    /// 
    /// </summary>
    void OnEnable() 
    {
        Application.logMessageReceived += Log;
    }

    /// <summary>
    /// 
    /// </summary>
    void OnDisable() 
    { 
        Application.logMessageReceived -= Log; 
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logString"></param>
    /// <param name="stackTrace"></param>
    /// <param name="type"></param>
    public void Log(string logString, string stackTrace, LogType type)
    {
        foreach (var line in logString.Split('\n'))
        {
            if (line.Length <= MAX_LINES_LENGTH)
            {
                lines.Add(line);
                continue;
            }

            var lineCount = line.Length / MAX_LINES_LENGTH + 1;
            for (int i = 0; i < lineCount; i++)
            {
                if ((i + 1) * MAX_LINES_LENGTH <= line.Length)
                {
                    lines.Add(line.Substring(i * MAX_LINES_LENGTH, MAX_LINES_LENGTH));
                }
                else
                {
                    lines.Add(line.Substring(i * MAX_LINES_LENGTH, line.Length - i * MAX_LINES_LENGTH));
                }
            }
        }

        if (lines.Count > MAX_LINES)
        {
            lines.RemoveRange(0, lines.Count - MAX_LINES);
        }

        logStr = string.Join("\n", lines);
    }

    /// <summary>
    /// 
    /// </summary>
    void OnGUI()
    {
        GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity,
           new Vector3(Screen.width / 1200.0f, Screen.height / 800.0f, 1.0f));
        GUI.Label(new Rect(10, 10, 800, 370), logStr, new GUIStyle() { fontSize = Math.Max(10, fontSize) });
    }
}
